<template>
  <div>
    <mt-header title="注册">
      <mt-button icon="back" slot="left"  @click="$router.push('/')"></mt-button>
      <router-link to="/login" slot="right">登录</router-link>
    </mt-header>
    <!-- 表单 -->
    <mt-field
      label="用户名"
      placeholder="请输入用户名"
      v-model="name"
      @blur.native.capture="checkName"
      :state="nameState"
    ></mt-field>
    <mt-field
      label="密码"
      type="password"
      placeholder="请输入密码"
      v-model="pwd"
      :state="pwdState"
      @blur.native.capture="checkPwd"
    ></mt-field>
    <mt-field
      label="确认密码"
      type="password"
      placeholder="请再次输入密码"
      v-model="pwd2"
      :state="pwd2State"
      @blur.native.capture="checkPwd2"
    ></mt-field>
    <mt-button type="primary" size="large" @click="checkForm"
      >快速注册</mt-button
    >
  </div>
</template>

<script>
export default {
  watch: {
    name() {
      this.checkName();
    },
  },
  methods: {
    checkForm() {
      if (this.checkName() && this.checkPwd() && this.checkPwd2()) {
        console.log("验证成功,执行注册业务...");
        // 发送post请求,执行注册业务
        let params = `username=${this.name}&userpwd=${this.pwd}`;
        this.axios.post("/zhuce/register", params).then((res) => {
          console.log(res);
          if (res.data.code == 200) {
            this.$router.push("/login");
          } else {
            this.$messagebox("提示", "用户已存在");
          }
        });
      }
    },
    checkPwd2() {
      let exp = /^\d{6}$/;
      if (exp.test(this.pwd2) && this.pwd2 == this.pwd) {
        this.pwd2State = "success";
        return true;
      } else {
        this.pwd2State = "error";
        return false;
      }
    },
    checkPwd() {
      let exp = /^\d{6}$/;
      if (exp.test(this.pwd)) {
        this.pwdState = "success";
        return true;
      } else {
        this.pwdState = "error";
        return false;
      }
    },
    checkName() {
      //验证用户名   6~15位
      let exp = /^\w{6,15}$/;
      if (exp.test(this.name)) {
        this.nameState = "success";
        return true;
      } else {
        this.nameState = "error";
        return false;
      }
    },
  },
  data() {
    return {
      name: "", //绑定用户名
      nameState: "", //绑定状态
      pwd: "",
      pwdState: "",
      pwd2: "",
      pwd2State: "",
    };
  },
};
</script>

<style lang="scss" scoped>
</style>